package cn.wh.controller;

import cn.wh.enums.OperatorFriendRequestTypeEnum;
import cn.wh.pojo.ChatMsg;
import cn.wh.pojo.FriendsRequest;
import cn.wh.pojo.MyFriends;
import cn.wh.pojo.User;
import cn.wh.service.UserServer;
import cn.wh.utils.FastDFSClient;
import cn.wh.utils.FileUtils;
import cn.wh.utils.JSONResult;
import cn.wh.utils.MD5Utils;
import cn.wh.vo.MyFriendsVO;
import cn.wh.vo.UserVo;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2021/2/4 18:40
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServer userServer;

    @Autowired
    FastDFSClient fastDFSClient;


    @RequestMapping("/uploadFaceBase64")
    //用户头像上传访问方法
    public JSONResult uploadFaceBase64(@RequestParam("userId") String userId, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        User userResult = null;
        try {
            //打印用户上传图片
            System.out.println(file);
            //打印用户的id
            System.out.println(userId);
            StorePath storePath = fastDFSClient.uploadBase64(file);
            //用户原图片路径
            String path = "/" + storePath.getFullPath();
            System.out.println(path);
            //获取_150x150的图片路径
            String[] split = path.split("\\.");
            String img150x150 = split[0] + "_150x150." + split[1];
            User user = new User();
            user.setId(userId);
            user.setFaceImageBig(path);
            user.setFaceImage(img150x150);
            userResult = userServer.updateUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg("文件不可大于100MB");
        }
        return JSONResult.ok(userResult);
    }


    //修改昵称
    @PostMapping("/updateNickname")
    public JSONResult updateNickname(User user) {
        User userResult = userServer.updateUser(user);
        return JSONResult.ok(userResult);
    }

    //登录
    @PostMapping("/login")
    public JSONResult login(User user) {
        User userResult = userServer.queryUserNameIsExit(user.getUsername());
        if (userResult == null) {
            return JSONResult.errorMap("该用户不存在");
        }
        //此用户存在可以登录
        if (!userResult.getPassword().equals(MD5Utils.getPwd(user.getPassword()))) {
            return JSONResult.errorMap("密码错误");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userResult, userVo);
        return JSONResult.ok(userVo);
    }


    //用户登录一体化方法
    @PostMapping("/registerOrLogin")
    public JSONResult registerOrLogin(User user) {
        User userResult = userServer.queryUserNameIsExit(user.getUsername());
        if (userResult != null) {
            //此用户存在可以登录
            if (!userResult.getPassword().equals(MD5Utils.getPwd(user.getPassword()))) {
                return JSONResult.errorMap("密码错误");
            }
        } else {
            //注册并且登录
            userResult = userServer.insert(user);
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userResult, userVo);
        return JSONResult.ok(userVo);
    }

    //添加好友
    @PostMapping("/addUser")
    public JSONResult addUser(@RequestParam("sendUserId") String sendUserId,
                              @RequestParam("acceptUserId") String acceptUserId) {
        //判断是不是自己 不能添加自己为好友
        if (sendUserId.equals(acceptUserId)) {
            return JSONResult.ok("不能添加自己为好友");
        } else {
            //查询对方是否已经是好友
            int i = userServer.queryToMyFriend(sendUserId, acceptUserId);
            //不是好友可以添加
            if (i == 0) {
                //查询是否已经发送
                int sendFriendRequest = userServer.isSendFriendRequest(sendUserId, acceptUserId);
                if (sendFriendRequest == 0) {
                    //发送好友请求
                    if (userServer.sendFriendRequest(sendUserId, acceptUserId) > 0) {
                        return JSONResult.ok("发送好友请求成功");
                    } else {
                        return JSONResult.errorMsg("发送好友请求失败");
                    }
                } else {
                    return JSONResult.ok("不可以重复发送好友请求");
                }
            } else {
                return JSONResult.ok("你们已经是好友关系");
            }
        }
    }


    //搜索好友
    @PostMapping("/searchUsername")
    public JSONResult searchUsername(@RequestParam("username") String username) {
        UserVo userResult = userServer.queryAllUser(username);

        return JSONResult.ok(userResult);
    }


    //根据某一个用户查询添加好友请求消息条数
    @PostMapping("/queryRequestMsgCount")
    public JSONResult queryRequestMsgCount(@RequestParam("id") String id) {
        int count = userServer.queryRequestMsgCount(id);
        return JSONResult.ok(count);
    }


    @GetMapping("/getUser")
    public String getUsetById(String id, Model model) {
        User user = userServer.getUserById(id);
        model.addAttribute("user", user);
        return "user_list";
    }


    //查询某一个用户所有的请求消息对象数据
    @PostMapping("/queryRequestMsgList")
    public JSONResult queryRequestMsgList(String id) {
        List<UserVo> userVoList = userServer.queryRequestMsgList(id);
        return JSONResult.ok(userVoList);
    }


    //签收消息 单签
    @PostMapping("/signMessage")
    public void signMessage(String msgId) {
        userServer.signMessage(msgId);
    }

    //处理好友
    @PostMapping("/operFirendRequest")
    public JSONResult operFirendRequest(String accpetUserId, String sendUserId, Integer operType) {
        FriendsRequest friendsRequest = new FriendsRequest();
        friendsRequest.setAcceptUserId(accpetUserId);
        friendsRequest.setSendUserId(sendUserId);
        if (operType.equals(OperatorFriendRequestTypeEnum.IGNORE.type)) {
            //拒绝 将对请求表进行删除。
            userServer.deleteFriendRequest(friendsRequest);
        } else if (operType.equals(OperatorFriendRequestTypeEnum.PASS.type)) {
            //通过 将对好友表添加一条记录 同时删除好友请求数据
            userServer.deleteFriendRequest(friendsRequest);
            userServer.insertFriendInfo(accpetUserId, sendUserId);
        }
        //根据某一个用户查询好友表的数据
        List<MyFriendsVO> myFriendsVOS = userServer.queryMyFriends(accpetUserId);

        return JSONResult.ok(myFriendsVOS);
    }


    /**
     * 好友列表查询
     *
     * @param id
     * @return
     */
    @PostMapping("/myFriends")
    public JSONResult myFriends(String id) {
        List<MyFriendsVO> myFriendsVOS = userServer.queryMyFriends(id);
        return JSONResult.ok(myFriendsVOS);
    }

    /**
     * 查询未签收的消息
     *
     * @param myId
     * @return
     */
    @PostMapping("/queryUnSignMsg")
    public JSONResult queryUnSignMsg(String myId) {
        List<ChatMsg> msgList = userServer.queryUnSignMsg(myId);
        return JSONResult.ok(msgList);
    }

}
